package se.thoka.twt.client.utils.validation;

/**
 * <p>
 * Asserts that the value has at least a minimum length.
 * </p>
 * 
 * @author Thobias Karlsson, Thoka
 * @since 9 jan 2010
 */
public class MaxLengthValidation implements Validation {

	private String message;
	private int maxLength;

	/**
	 * Creates a new instance of {@link MaxLengthValidation}.
	 * 
	 * @param length
	 *            The maximum length.
	 */
	public MaxLengthValidation(int length) {
		this(length, ValidationUtil.getStrings().maxLengthExceeded(
				Integer.toString(length)));
	}

	/**
	 * Creates a new instance of {@link MaxLengthValidation}.
	 * 
	 * @param maxLength
	 *            The maximum length.
	 * @param message
	 *            The message where <code>{0}</code> is replaced with
	 *            <code>length</code>.
	 */
	public MaxLengthValidation(int maxLength, String message) {
		this.maxLength = maxLength;

		if (message != null) {
			message = message.replaceAll("\\{0\\}", String.valueOf(maxLength));
		}
		this.message = message;
	}

	/**
	 * @return The maximum length.
	 */
	public int getMaxLength() {
		return maxLength;
	}

	@Override
	public boolean validate(String value) {
		return value == null || value.length() <= maxLength;
	}

	@Override
	public String getDescription() {
		return message;
	}
}
